package com.migu.contacts.util;

import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;

import java.util.ArrayList;
import java.util.List;

public class CheckBoxUtil {
    public static void checkOne(CheckBox... arr) {
        for (CheckBox checkBox : arr) {
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        for (CheckBox box : arr) {
                            if (box != buttonView) {
                                box.setChecked(false);
                            }
                        }
                    }
                }
            });
        }
    }

    public static int getCheckedIndex(ViewGroup group) {
        List<CheckBox> checkBoxList = getCheckBoxList(group);
        for (int i = 0; i < checkBoxList.size(); i++) {
            if (checkBoxList.get(i).isChecked()) {
                return i;
            }
        }
        return -1;
    }

    public static void checkIndex(ViewGroup group, int index) {
        List<CheckBox> checkBoxList = getCheckBoxList(group);
        if (index < 0 || index >= checkBoxList.size()) {
            return;
        }
        checkBoxList.get(index).setChecked(true);
    }

    public static void checkOne(ViewGroup group) {
        List<CheckBox> list = getCheckBoxList(group);
        for (CheckBox checkBox : list) {
            checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        for (CheckBox box : list) {
                            if (box != buttonView) {
                                box.setChecked(false);
                            }
                        }
                    }
                }
            });
        }
    }

    private static @NonNull List<CheckBox> getCheckBoxList(ViewGroup group) {
        List<CheckBox> list = new ArrayList<>();
        for (int i = 0; i < group.getChildCount(); i++) {
            View childAt = group.getChildAt(i);
            if (childAt instanceof CheckBox) {
                list.add((CheckBox) childAt);
            }
        }
        return list;
    }
}
